package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())) {
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (apUser==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"请检查您的手机号");
        }
        String password = apUser.getPassword();
        String salt = apUser.getSalt();
        String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!password.equals(newPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"手机号或密码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        apUser.setPassword("");
        apUser.setSalt("");
        map.put("token", AppJwtUtil.getToken(Long.valueOf(apUser.getId())));
        map.put("user",apUser);

        return ResponseResult.okResult(map);
        }else {
            //暂不登录
            if (dto.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));

            return ResponseResult.okResult(map);
        }
    }
}
